part of 'database_helper.dart';

class TodoDao {
  final String _tableName = 'todos';
  final String _id = 'id';
  final String _completeDate = 'completeDate';
  final String _completeDateStr = 'completeDateStr';
  final String _content = 'content';
  final String _date = 'date';
  final String _dateStr = 'dateStr';
  final String _priority = 'priority';
  final String _status = 'status';
  final String _title = 'title';
  final String _type = 'type';
  final String _userId = 'userId';

  Future<void> createTable(Database db) async {
    db.execute('CREATE TABLE $_tableName('
        '$_id integer PRIMARY KEY AUTOINCREMENT,'
        '$_completeDate integer,'
        '$_completeDateStr TEXT,'
        '$_content TEXT,'
        '$_date integer,'
        '$_dateStr TEXT,'
        '$_priority integer default 0,'
        '$_status integer default 0,'
        '$_title integer,'
        '$_type integer default 0,'
        '$_userId integer'
        ')');
  }

  // 添加待办
  Future<int> insertTodo(TodoEntity todo) async {
    final db = await DatabaseHelper().database;
    return await db.insert(
      _tableName,
      todo.toJson(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  // 获取待办列表
  Future<List<TodoEntity>> getTodos() async {
    final db = await DatabaseHelper().database;
    final List<Map<String, dynamic>> maps = await db.query(_tableName);
    return List.generate(maps.length, (i) => TodoEntity.fromJson(maps[i]));
  }

  // 更新待办
  Future<int> updateTodo(TodoEntity todo) async {
    final db = await DatabaseHelper().database;
    return await db.update(
      _tableName,
      todo.toJson(),
      where: '$_id = ?',
      whereArgs: [todo.id],
    );
  }

  // 删除待办
  Future<int> deleteTodo(int id) async {
    final db = await DatabaseHelper().database;
    return await db.delete(
      _tableName,
      where: '$_id = ?',
      whereArgs: [id],
    );
  }
}
